<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SmsController extends Controller
{
    /**
     * 获取短信验证码
     * @param $mobile
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCode($mobile)
    {
        $today = strtotime('today');
        $ip = \Illuminate\Support\Facades\Request::ip();
        $num = DB::table('mobile_ip')->where('ip', $ip)->where('create_time', '>=', $today)->count();
        if ($num >= 10) {
            return response()->json(['status' => 0, 'msg' => '该设备暂不可发送短信验证码！']);
        }

        DB::table('mobile_ip')->insert(['ip' => $ip, 'mobile' => $mobile, 'create_time' => time()]);

        $mInfo = DB::table('mobile_code')->where('mobile', $mobile)->first();
        if ($mInfo && time() - $mInfo->update_time < 60) {
            return response()->json(['status' => 0, 'msg' => '一分钟之内不可再次发送！']);
        }
        $code = mt_rand(1000, 9999);
        $content = urlencode("您的验证码{$code}，该验证码1分钟内有效，请勿泄漏于他人！【酒书】");
        $result = self::sendMsg($mobile, $content);
        if (!$result || $result < 0) {
            return response()->json(['status' => 0, 'msg' => '发送失败！']);
        }

        if ($mInfo) {
            DB::table('mobile_code')->where('id', $mInfo->id)->update(['code' => $code, 'update_time' => time(), 'status' => 0]);
        } else {
            DB::table('mobile_code')->insert(['mobile' => $mobile, 'code' => $code, 'create_time' => time(), 'update_time' => time(), 'status' => 0]);
        }

        return response()->json(['status' => 1, 'msg' => '验证码已发送']);

    }

    /**
     * 校验短信验证码
     * @param $mobile
     * @param $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkCode($mobile, $code)
    {
        $mInfo = DB::table('mobile_code')->where('mobile', $mobile)->first();
        if (!$mInfo) {
            return ['status' => 0, 'msg' => '该手机号码不存在！'];
        }
        if ($mInfo->status == 1) {
            return ['status' => 0, 'msg' => '该验证码已失效！'];
        }

        if ($mInfo->code != $code) {
            return ['status' => 0, 'msg' => '短信验证码错误！'];
        }

        DB::table('mobile_code')->where('id', $mInfo->id)->update(['status' => 1]);
        return ['status' => 1];
    }

    /**
     * 发送短信
     * @param $mobile
     * @param $content
     * @return bool|string
     */
    public function sendMsg($mobile, $content)
    {
        $msg = rawurlencode(mb_convert_encoding($content, "gb2312", "utf-8"));
        $uid = 'ZZJS011657';
        $passwd = '2E1322';
        $gateway = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID={$uid}&Pwd={$passwd}&Mobile={$mobile}&Content={$msg}&Cell=&SendTime=";
        $result = file_get_contents($gateway);

        return $result;
    }

}
